<?php

class DetalleprocesoController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	 
	
	 
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','eliminar'),
				'users'=>array('@'),
				'expression'=>'(Yii::app()->user->idPerfilUsuario == (1))'
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		  
$model->idUsuario = Yii::app()->user->id; 
$usuario=$model->idUsuario;


$sql="SELECT idProceso FROM proceso WHERE idUsuario='$usuario' ORDER BY CAST(idProceso AS UNSIGNED)  DESC LIMIT 1";
$num_proceso=Proceso::model()->findBySql($sql);




$procesonumero=$num_proceso['idProceso']+1;//aumentar ACA



$sql2=

"SELECT idDetalleProceso FROM detalleproceso WHERE idProceso='$procesonumero' AND idUsuario='$usuario' ORDER BY CAST(idDetalleProceso AS UNSIGNED) DESC LIMIT 1";
$num_detalleproceso=DetalleProceso::model()->findBySql($sql2);


$detprocesonumero=$num_detalleproceso['idDetalleProceso']+1;

            
            
            
            
            
            
            
            
            
            
            
            
            
		$model=new Detalleproceso;

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		//if(isset($_POST['Detalleproceso']))
		//{
			//$model->attributes=$_POST['Detalleproceso'];
			//if($model->save())
				//$this->redirect(array('view','id'=>$model->idDetalleProceso));
		//}

		//$this->render('create',array(
			//'model'=>$model,
		//));
		
		if(isset($_POST['Detalleproceso']))
        {   //$model2=new Proceso();
            $model->attributes=$_POST['Detalleproceso'];
           // $model2->attributes=$_POST['Proceso'];
			
			$tipoproceso=$_POST['tipoproceso'];
			
			if($model->save())
            {
			
		
                $cantidadstock="SELECT cantidad from producto where idProducto='$model->idProducto'";
                $cantidadstock= Producto::model()->findBySql($cantidadstock);
                $cantidadstock=$cantidadstock["cantidad"];
               $cantidad=$model->cantidad; 
   if($tipoproceso>=2){	            
               $cantidadactual=$cantidadstock-$cantidad;
                
            $sql="UPDATE producto SET cantidad=$cantidadactual where idProducto='$model->idProducto'";
				}
				
				if($tipoproceso==1){	            
               $cantidadactual=$cantidadstock+$cantidad;
                
            $sql="UPDATE producto SET cantidad=$cantidadactual where idProducto='$model->idProducto'";
				}
////mysql_query($sql) or die(mysql_error());
//
$connection=Yii::app()->db; 
$command=$connection->createCommand($sql);

$rowCount=$command->execute(); // execute the non-query SQL
$dataReader=$command->query(); // execute a query SQL

		
                
                if (Yii::app()->request->isAjaxRequest)
                {
                    echo CJSON::encode(array(
                        'status'=>'success', 
                        'div'=>"Detalleproceso successfully added"
                        ));
                    exit;               
                }
                else
                    $this->redirect(array('view','id'=>$model->id));
            }
        }
 
        if (Yii::app()->request->isAjaxRequest)
        {
            echo CJSON::encode(array(
                'status'=>'failure', 
                'div'=>$this->renderPartial('_form', array('model'=>$model,'detprocesonumero'=>$detprocesonumero), true)));
                 
            exit;               
        }
        else
            $this->render('create',array('model'=>$model,'detprocesonumero'=>$detprocesonumero));
		
	}

	

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id,$id2,$id3)
	{
	
	
		$model=$this->loadModel($id,$id2,$id3);
		
        if( isset( $_POST['Detalleproceso'] ) )
  {
  	//$model=new Detalleproceso;
    $model->attributes = $_POST['Detalleproceso'];
    
	if( $model->save() )
    {
      if( Yii::app()->request->isAjaxRequest )
      {
        // Stop jQuery from re-initialization
       // Yii::app()->clientScript->scriptMap['jquery.js'] = false;
 
        echo CJSON::encode( array(
          'status' => 'success',
          'content' => 'ModelName successfully updated',
        ));
        exit;
      }
      else
        $this->redirect( array( 'view', 'id' => $model->idDetalleProceso ) );
    }
  }
 
  if( Yii::app()->request->isAjaxRequest )
  {
    // Stop jQuery from re-initialization
   // Yii::app()->clientScript->scriptMap['jquery.js'] = false;
 
    echo CJSON::encode( array(
      'status' => 'failure',
      'content' => $this->renderPartial( '_formupdate', array('model' => $model ), true, true ),
    ));
    exit;
  }
  else
    $this->render( 'update', array( 'model' => $model ) );
	

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

	//	if(isset($_POST['Detalleproceso']))
		//{
			//$model->attributes=$_POST['Detalleproceso'];
			//if($model->save())
				//$this->redirect(array('view','id'=>$model->idDetalleProceso));
		//}

		//$this->render('update',array(
			//'model'=>$model,
		//));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	
       
        
        
        
        public function actionDelete($id,$id2,$id3,$tp)
	{
		
                
                $model=$this->loadModel($id,$id2,$id3);
		
                 $this->performAjaxValidation($model);
		
                //$this->loadModel($id,$id2,$id3)->delete();
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		//if(!isset($_GET['ajax']))
			//$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
			
			//$model = $this->loadModel($id,$id2,$id3);
  if( Yii::app()->request->isAjaxRequest )
  {
    // Stop jQuery from re-initialization
   // Yii::app()->clientScript->scriptMap['jquery.js'] = false;
   


 $cantidadstock="SELECT cantidad from producto where idProducto='$model->idProducto'";
 $cantidadstock= Producto::model()->findBySql($cantidadstock);
                $cantidadstock=$cantidadstock["cantidad"];
               $cantidad=$model->cantidad; 
   if($tp>=2 ){	            
               $cantidadactual=$cantidadstock+$cantidad;
                
            $sql="UPDATE producto SET cantidad=$cantidadactual where idProducto='$model->idProducto'";
				}
				
				if($tp==1){	            
               $cantidadactual=$cantidadstock-$cantidad;
                
            $sql="UPDATE producto SET cantidad=$cantidadactual where idProducto='$model->idProducto'";
				}
				if($tp==0)
				{
                $cantidadactual=$cantidadstock;
                
            $sql="UPDATE producto SET cantidad=$cantidadactual where idProducto='$model->idProducto'";
			

				}



    if( isset( $_POST['action'] ) && $_POST['action'] == 'confirmDelete' )
    {
         	

      if($model->delete()){

  

$connection=Yii::app()->db; 
$command=$connection->createCommand($sql);

$rowCount=$command->execute(); // execute the non-query SQL
$dataReader=$command->query(); // execute a query SQL

	

      echo CJSON::encode( array(
        'status' => 'success',
        'content' => 'Registro eliminado',
      ));
      exit;
      }

    }
    else if( isset( $_POST['action'] ))
    {
      echo CJSON::encode( array(
        'status' => 'canceled',
        'content' => 'Cancelado',
      ));
      exit;
    }
    else
    {
      echo CJSON::encode( array(
        'status' => 'failure',
        'content' => $this->renderPartial( 'delete', array(
          'model' => $model
           ), true, true ),
      ));
      exit;
    }
  }
  else
  {
    if( isset( $_POST['confirmDelete'] ) )
    {
      // execute a query SQL

      $this->redirect( array( 'admin' ) );
    }
    else if( isset( $_POST['denyDelete'] ) )
      $this->redirect( array( 'view', 'id' => $model->id ) );
    else
      $this->render( 'delete', array( 'model' => $model ) );
  }
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Detalleproceso');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Detalleproceso('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Detalleproceso']))
			$model->attributes=$_GET['Detalleproceso'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Detalleproceso the loaded model
	 * @throws CHttpException
	 */
		public function loadModel($id,$id2,$id3)
	{
		$model=Detalleproceso::model()->findByPk(array('idDetalleProceso'=>$id, 'idProceso'=>$id2,'idUsuario'=>$id3));
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Detalleproceso $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='detalleproceso-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionEliminar($id,$id2)
	{
		
                
                $model=$this->loadModel2($id,$id2);
                
  //$val=count($model);
  Yii::app()->db->createCommand("delete from detalleproceso where idProceso='$id' and idUsuario='$id2'")->query();
               // $this->loadModel2($id,$id2)->delete();
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
	$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('proceso/create'));
                
                
	}
        
        	public function loadModel2($id,$id2)
	{
		$model=Detalleproceso::model()->find('idProceso='.$id AND 'idUsuario='.$id2);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
